package com.myfoon.model.helper;


import com.myfoon.model.cacheable.UserCache;
import com.myfoon.model.cacheable.UserSecurityCache;
import com.myfoon.model.entity.User;
import com.myfoon.model.exception.PasswordNotMatchException;

import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;

import javax.persistence.NoResultException;


public class UserCacheHelper {
    public UserCacheHelper() {
    }
    
    public void put(User user) {        
        NamedCache userCacheService = CacheFactory.getCache("User");
        NamedCache userSecurityService = CacheFactory.getCache("UserSecurity");
        
        UserCache userCache = new UserCache(user);
        
        userSecurityService.put(userCache.getEmail(), new UserSecurityCache(userCache.getId(), userCache.getPasswd()));        
        userCacheService.put(userCache.getId(), userCache);        
    }
    
    public User findByEmailAndPassword(String email, String passwd) throws NoResultException,
                                                             PasswordNotMatchException {
        NamedCache userCacheService = CacheFactory.getCache("User");        
        NamedCache userSecurityService = CacheFactory.getCache("UserSecurity");
                        
        Object userSecurity = userSecurityService.get(email);
        
        if (userSecurity != null) {            
            UserSecurityCache us = (UserSecurityCache)userSecurity;        
            
            if (us.getPassword().equals(passwd)) {                      
                UserCache userCache = (UserCache)(userCacheService.get(us.getId()));   
                return userCache.toUser();
            }
            else {                
                throw new PasswordNotMatchException(); 
            }            
        }
        else {            
            return null;
        }       
    }            
}
